<template>
  <!-- 现场检查弹窗 -->
  <el-dialog v-model="checkModalVisible" title="现场检查" width="1200px" :before-close="handleClose">
    <div class="form-title-wrapper">
      <div class="form-title-text">现场检查笔录</div>
      <el-button class="btn" :loading="preViewLoading" @click="handleViewRecord">预览</el-button>
    </div>
    <DynamicForm
      ref="queryRefCheck"
      v-model="formData"
      :disabled="checkBtnType === 'view'"
      :config="formConfigCheck"
      :items="formItemsCheck"
      :dict-data="{ sys_user_sex, check_person }">
      <template #inspectorId1>
        <el-select
          v-model="formData.inspectorId1"
          clearable
          filterable
          placeholder="请选择检查人"
          @change="handleInspector1">
          <el-option
            v-for="(item, index) in check_person"
            :key="item.value"
            :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </template>
      <template #inspectorId2>
        <el-select
          v-model="formData.inspectorId2"
          clearable
          filterable
          placeholder="请选择检查人"
          @change="handleInspector2">
          <el-option
            v-for="(item, index) in check_person"
            :key="item.value"
            :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </template>
      <template #recorderId>
        <el-select
          v-model="formData.recorderId"
          clearable
          filterable
          placeholder="请选择记录人"
          @change="handleRecorderName">
          <el-option
            v-for="(item, index) in check_person"
            :key="item.value"
            :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </template>
      <template #checkDate="{ item }">
        <!-- :disabled-date="disabledDate" -->
        <el-date-picker
          v-model="formData.checkDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :style="item.style"
          @change="handleDateChange" />
      </template>
      <template #streetOfLocation>
        <el-row :gutter="20">
          <el-col :span="7">
            <el-input :value="settings.cityName" disabled placeholder="城市"></el-input>
          </el-col>
          <el-col :span="7">
            <el-input :value="settings.areaName" disabled placeholder="区县"></el-input>
          </el-col>
          <el-col :span="10">
            <el-select v-model="formData.streetOfLocation" clearable filterable placeholder="请选择街道">
              <el-option
                v-for="(item, index) in street_of_area"
                :key="item.value"
                :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-col>
        </el-row>
      </template>
      <template #location>
        <el-input v-model="formData.location" placeholder="详细地址"></el-input>
      </template>
      <template #companyAddress="{ item }">
        <el-row :gutter="20">
          <el-col :span="7">
            <el-input :value="settings.cityName" disabled placeholder="城市"></el-input>
          </el-col>
          <el-col :span="7">
            <el-input :value="settings.areaName" disabled placeholder="区县"></el-input>
          </el-col>
          <el-col :span="10">
            <el-select
              v-model="formData.streetOfCompanyAddress"
              clearable
              filterable
              :disabled="item.props.disabled"
              placeholder="请选择街道">
              <el-option
                v-for="(item, index) in street_of_area"
                :key="item.value"
                :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-col>
        </el-row>
      </template>
      <template #streetOfCompanyAddress="{ item }">
        <el-input v-model="formData.companyAddress" :disabled="item.props.disabled" placeholder="详细地址"></el-input>
      </template>
      <template #partyId>
        <el-select
          v-model="formData.partyId"
          filterable
          remote
          clearable
          reserve-keyword
          placeholder="请输入当事人名称"
          :disabled="partyDisabled"
          :remote-method="handlepartySearch"
          :loading="partyLoading"
          style="width: calc(100% - 45px); margin-right: 6px"
          @change="handlepartyChange">
          <el-option v-for="item in partyOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-button link type="primary" :disabled="partyDisabled" @click="handlePartyAdd">添加</el-button>
      </template>
      <template #companyProfile>
        <!-- 企业情况 -->
        <SmartTextInput
          v-model="formData.companyProfile"
          type="textarea"
          :rows="4"
          placeholder="请输入企业情况，输入关键词后按Tab键快速补全"
          :min-length="2"
          :max-suggestions="5"
          contentType="4"
          @select="handleSuggestionSelect" />
      </template>
      <template #siteDescription>
        <!-- 检查情况 -->
        <SmartTextInput
          v-model="formData.siteDescription"
          type="textarea"
          :rows="4"
          placeholder="请输入现场情况，输入关键词后按Tab键快速补全"
          :min-length="2"
          :max-suggestions="5"
          contentType="5"
          @select="handleSuggestionSelect" />
      </template>
      <!-- 现场留证情况 -->
      <template #siteRetention>
        <SmartTextInput
          v-model="formData.siteRetention"
          type="textarea"
          :rows="4"
          placeholder="请输入现场留证情况，输入关键词后按Tab键快速补全"
          :min-length="2"
          :max-suggestions="5"
          contentType="6"
          @select="handleSuggestionSelect" />
      </template>
    </DynamicForm>
    <div class="form-title-wrapper">
      <div class="form-title-text">现场检查照片</div>
      <el-button :disabled="checkBtnType === 'view'" class="btn" @click="handleAddImg">添加</el-button>
    </div>
    <imgGroup ref="imgGroupRef" :id="id" :formData="formData" :disabled="checkBtnType === 'view'" />
    <label class="el-form-item__label" style="font-size: 14px">是否上传附件</label>
    <el-radio-group v-model="formData.isFile" :disabled="checkBtnType === 'view'">
      <el-radio label="0" size="large">否</el-radio>
      <el-radio label="1" size="large">是</el-radio>
    </el-radio-group>
    <!-- 附件 -->
    <FileList
      v-if="formData.isFile === '1'"
      :disabled="checkBtnType === 'view'"
      :fileUploadList="formData.ttsiteInspectionRecordFilesList" />
    <template #footer>
      <div class="form-footer">
        <el-button v-if="checkBtnType !== 'view'" type="primary" @click="handleSave">保存</el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 添加当事人信息 -->
  <partyDetail v-model:value="partyOpen" title="添加当事人信息" @getList="setParty" />
</template>

<script setup lang="ts">
import { ref, computed, getCurrentInstance, onMounted, watch } from 'vue'
import DynamicForm from '@/components/DynamicForm/index.vue'
import { useTableColumns } from './config'
import imgGroup from './imgGroup.vue'
import FileList from '@/components/FileList/index.vue'
import SmartTextInput from '@/components/SmartTextInput/index.vue'
import { onSiteInspectionSave, onSiteInspectionDetail, onSiteInspectionUpdate } from '@/api/onSiteInspection/index.js'
import settings from '@/settings.js'
import { onSiteInspectionPreviewPdf } from '@/api/system/file.js'
import { ElMessage } from 'element-plus'
import { listPartyinfo } from '@/api/partyinfo/index'
import { getUserEnforcementNo } from '@/api/system/user.js'
import partyDetail from '@/views/workbench/filingReview/party/detail.vue'

const props = defineProps({
  modalvalue: {
    type: Boolean,
    required: true,
  },
  id: {
    type: [String, Number],
    default: '',
  },
  checkBtnType: {
    required: true,
    type: String,
    default: 'edit', // edit查看编辑 view查看
  },
  partyId: {
    type: [String, Number],
    default: '',
  },
})

const { proxy } = getCurrentInstance()
const { sys_user_sex, street_of_area } = proxy.useDict('sys_user_sex', 'street_of_area')
const check_person = ref<any>([])
const imgGroupRef = ref<any>(null)
const { formConfigCheck, formItemsCheck } = useTableColumns()
const emit = defineEmits(['update:modalvalue', 'handleSave'])
const checkModalVisible = computed({
  get: () => props.modalvalue,
  set: (val: boolean) => {
    queryRefCheck.value?.resetValidation()
    emit('update:modalvalue', val)
  },
})
const partyDisabled = computed(() => {
  const boo = props.partyId !== '' && props.partyId !== null && props.partyId !== undefined
  if (boo) {
    formData.value.partyId = props.partyId
    handlepartyChange(props.partyId)
  }
  return boo
})
const getUserList = async () => {
  const res = await getUserEnforcementNo({})
  if (res.data.length > 0) {
    check_person.value = res.data.map((item: any) => {
      return { value: item.userId, label: item.name, enforcementNo: item.enforcementNo }
    })
  }
}
getUserList()
const initFormData = {
  location: undefined,
  inspectorId1: undefined,
  inspectorName1: undefined,
  inspectorCertNo1: undefined,
  inspectorId2: undefined,
  inspectorName2: undefined,
  inspectorCertNo2: undefined,
  recorderId: undefined,
  recorderName: undefined,
  recorderCertNo: undefined,
  workUnit: '北京市大兴区生态环境局',
  legalRepresentative: undefined,
  sitePrincipalName: undefined,
  sitePrincipalBirth: undefined,
  sitePrincipalGender: undefined,
  sitePrincipalPhone: undefined,
  sitePrincipalIdNo: undefined,
  sitePrincipalJob: undefined,
  companyName: undefined,
  companyAddress: undefined,
  postalCode: undefined,
  siteDescription: undefined,
  ttsiteInspectionRecordPhotosList: [
    {
      groupName: '现场检查照片',
      photos: '',
      evidenceTarget: undefined,
      photoTime: undefined,
      address: {
        streetOfPhotoLocation: undefined,
        photoLocation: undefined,
      },
    },
  ],
  isFile: '0',
  ttsiteInspectionRecordFilesList: [
    {
      groupName: '',
      files: '',
    },
  ],
}

const formData = ref<any>(initFormData)
const handleInspector1 = val => {
  if (val === formData.value.inspectorId2) {
    formData.value.inspectorId1 = undefined
    formData.value.inspectorCertNo1 = undefined
    formData.value.inspectorName1 = undefined
    return
  }
  check_person.value.forEach(item => {
    if (item.value === val) {
      formData.value.inspectorName1 = item.label
      formData.value.inspectorCertNo1 = item.enforcementNo
    }
  })
}
const handleInspector2 = val => {
  if (val === formData.value.inspectorId1) {
    formData.value.inspectorId2 = undefined
    formData.value.inspectorCertNo2 = undefined
    formData.value.inspectorName2 = undefined
    return
  }
  check_person.value.forEach(item => {
    if (item.value === val) {
      formData.value.inspectorName2 = item.label
      formData.value.inspectorCertNo2 = item.enforcementNo
    }
  })
}
const handleRecorderName = val => {
  check_person.value.forEach(item => {
    if (item.value === val) {
      formData.value.recorderCertNo = item.enforcementNo
      formData.value.recorderName = item.label
    }
  })
}
// 现场检查详情
const getDetail = async (id: string | number) => {
  const res = await onSiteInspectionDetail(id)
  res.data.ttsiteInspectionRecordPhotosList.forEach(item => {
    item.address = {
      streetOfPhotoLocation: item.streetOfPhotoLocation,
      photoLocation: item.photoLocation,
    }
  })
  formData.value = res.data
  formData.value.inspectorId1 = String(res.data.inspectorId1)
  formData.value.inspectorId2 = String(res.data.inspectorId2)
  formData.value.checkDate = [res.data.inspectionStartTime, res.data.inspectionEndTime]
  delete formData.value.inspectionStartTime
  delete formData.value.inspectionEndTime
  formData.value.isFile = res?.data?.ttsiteInspectionRecordFilesList?.length ? '1' : '0'
  // formData.value.ttsiteInspectionRecordFilesList.forEach(item => {
  //   item.fileList = item.files.split(',')
  // })
}
watch(
  () => [props.id, props.modalvalue],
  newV => {
    if (newV[0]) {
      getDetail(newV[0])
    } else {
      formData.value = JSON.parse(JSON.stringify(initFormData))
    }
  },
  { immediate: true }
)
// 当事人搜索以及回显 start =========================================================
const partyLoading = ref(false)
const partyOptions = ref<Array<any>>([])
const handlepartySearch = async (query: string) => {
  partyLoading.value = true
  const res: any = await listPartyinfo({
    pageNum: 1,
    pageSize: 9999,
    partyName: query,
  })
  partyLoading.value = false
  partyOptions.value = res.rows.map(item => {
    return { value: String(item.id), label: item.partyName, ...item }
  })
}
handlepartySearch('')
// 添加当事人
const partyOpen = ref(false)
const handlePartyAdd = () => {
  partyOpen.value = true
}
// 当事人新增后回调
const setParty = async (form: any) => {
  await handlepartySearch('')
  partyOptions.value.forEach(item => {
    if (item.label === form.partyName) {
      formData.value.partyId = item.value
    }
  })
  formData.value.partyName = form.partyName
  formData.value.legalRepresentative = form.legalRepresentative
  formData.value.sitePrincipalName = form.onsiteName
  formData.value.sitePrincipalBirth = form.dateOfBirth
  formData.value.sitePrincipalGender = form.gender
  formData.value.sitePrincipalIdNo = form.idNumber
  formData.value.sitePrincipalPhone = form.onsitePhone
  formData.value.postalCode = form.postalCode
  formData.value.sitePrincipalWorkUnit = form.workUnit
  formData.value.sitePrincipalJob = form.onsitePosition
  formData.value.streetOfCompanyAddress = form.streetOfCompanyAddress
  formData.value.companyAddress = form.address

  // 清除回显字段的校验状态
  nextTick(() => {
    queryRefCheck.value?.validate()
  })
}
// 选择当事人
const handlepartyChange = (val: string) => {
  if (val) {
    partyOptions.value.forEach(item => {
      if (item.value === val) {
        const { legalRepresentative } = item
        formData.value.companyName = item.partyName
        formData.value.legalRepresentative = legalRepresentative
        formData.value.sitePrincipalName = item.onsiteName
        formData.value.sitePrincipalBirth = item.dateOfBirth
        formData.value.sitePrincipalGender = item.gender
        formData.value.sitePrincipalPhone = item.phone
        formData.value.sitePrincipalIdNo = item.idNumber
        formData.value.sitePrincipalWorkUnit = item.workUnit
        formData.value.sitePrincipalJob = item.legalPosition
        formData.value.companyAddress = item.address
        formData.value.streetOfCompanyAddress = item.streetOfCompanyAddress
        formData.value.postalCode = item.postalCode
      }
    })
  } else {
    formData.value.companyName = undefined
    formData.value.legalRepresentative = undefined
    formData.value.sitePrincipalName = undefined
    formData.value.sitePrincipalBirth = undefined
    formData.value.sitePrincipalGender = undefined
    formData.value.sitePrincipalPhone = undefined
    formData.value.sitePrincipalIdNo = undefined
    formData.value.sitePrincipalWorkUnit = undefined
    formData.value.sitePrincipalJob = undefined
    formData.value.companyAddress = undefined
    formData.value.streetOfCompanyAddress = undefined
    formData.value.postalCode = undefined
  }
  // 清除回显字段的校验状态
  nextTick(() => {
    queryRefCheck.value?.validate()
  })
}
// 当事人搜索以及回显 end =========================================================

// 预览现场检查文书
const preViewLoading = ref(false)
const handleViewRecord = async () => {
  const params = await handleSave(true)
  preViewLoading.value = true
  const res: any = await onSiteInspectionPreviewPdf(params)
  if (!!res.msg) {
    window.open(res.msg)
  } else {
    ElMessage.warning('预览文件不存在')
  }
  preViewLoading.value = false
}
// 添加现场检查照片
const handleAddImg = () => {
  // 确保数组存在，如果不存在则初始化
  formData.value.ttsiteInspectionRecordPhotosList.push({
    groupName: '现场检查照片',
    photos: undefined,
    evidenceTarget: undefined,
    photoTime: undefined,
    address: {
      streetOfPhotoLocation: undefined,
      photoLocation: undefined,
    },
  })
}

const handleClose = () => {
  formData.value.ttsiteInspectionRecordPhotosList = [{}]
  formData.value.isFile = '0'
  formData.value.ttsiteInspectionRecordFilesList = [
    {
      groupName: '',
      files: '',
    },
  ]
  checkModalVisible.value = false
}
const queryRefCheck = ref<any>(null)
const handleSave = (isPreView: Boolean = false) => {
  return new Promise(resolve => {
    Promise.all([queryRefCheck.value?.validate(), imgGroupRef.value.validateForm()]).then(async valid => {
      console.log('验证结果', formData.value)
      if (formData.value.inspectorId1 === formData.value.inspectorId2) {
        ElMessage.warning('检查人不能相同')
        return
      }
      if (valid[0] && valid[1]) {
        // 保存现场检查
        const params = JSON.parse(JSON.stringify(formData.value))
        params.ttsiteInspectionRecordPhotosList.forEach(item => {
          item.streetOfPhotoLocation = item.address.streetOfPhotoLocation
          item.photoLocation = item.address.photoLocation
          delete item.address
        })
        params.ttsiteInspectionRecordFilesList = params.ttsiteInspectionRecordFilesList.filter(item => {
          return item.files && item.files.length > 0
        })
        if (params.checkDate && params.checkDate.length === 2) {
          params.inspectionStartTime = params.checkDate[0]
          params.inspectionEndTime = params.checkDate[1]
        }
        if (isPreView === true) {
          resolve(params)
          return
        }
        let saveApi
        if (props.checkBtnType === 'edit' && props.id) {
          saveApi = onSiteInspectionUpdate
        } else {
          saveApi = onSiteInspectionSave
        }
        const res = await saveApi(params)
        emit('handleSave', { ...formData.value, id: res.msg })
        checkModalVisible.value = false
      }
    })
  })
}

const handleSuggestionSelect = (item: any) => {
  console.log('选择了建议:', item, formData.value.siteDescription)
}

// 当前选中的日期
const selectedDate = ref<Date | null>(null)

// 禁用不是同一天的日期
// const disabledDate = (time: Date) => {
//   if (!selectedDate.value) {
//     return false
//   }
//   // 只允许选择与已选日期相同的天
//   return (
//     time.getFullYear() !== selectedDate.value.getFullYear() ||
//     time.getMonth() !== selectedDate.value.getMonth() ||
//     time.getDate() !== selectedDate.value.getDate()
//   )
// }

// 处理日期变化
const handleDateChange = (value: any) => {
  if (value && value.length > 0) {
    // 记录第一个选择的日期
    selectedDate.value = new Date(value[0])
    console.log('选择的日期范围:', selectedDate.value)

    // 如果选择了两个日期且不是同一天，则重置
    if (value.length === 2) {
      const startDate = new Date(value[0])
      const endDate = new Date(value[1])

      const isSameDay =
        startDate.getFullYear() === endDate.getFullYear() &&
        startDate.getMonth() === endDate.getMonth() &&
        startDate.getDate() === endDate.getDate()

      if (!isSameDay) {
        // 自动调整结束时间为同一天
        const dateStr = value[0].split(' ')[0]
        const endTimeStr = value[1].split(' ')[1] || '23:59:59'
        formData.value.checkDate = [value[0], `${dateStr} ${endTimeStr}`]
      }
    }
  } else {
    // 清空选择时重置
    selectedDate.value = null
  }
}
</script>

<style scoped></style>
